package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.domain.Client;
import com.ruoyi.system.domain.ClientModel;
import com.ruoyi.system.domain.Pclient;
import com.ruoyi.system.service.IClientService;
import com.ruoyi.system.service.IPclientService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.file.tandc.TandcData1;
import com.ruoyi.web.controller.file.tandc.TandcData2;
import com.sushengren.easyword.EasyWord;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2023-11-01
 */
@RestController
@RequestMapping("/system/pclient")
public class PclientController extends BaseController
{
    @Resource
    private IPclientService pclientService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private SysPermissionService permissionService;

    /**
     * 下载T&C模板
     * @param clientModel
     * @return
     * @throws IOException
     */
    @PostMapping("/downloadClient")
    public AjaxResult downloadClient(@RequestBody @Validated ClientModel clientModel) {
        try {
            if (clientModel.getType() == 1) {
                // 查询pclient
//                Pclient pclient = pclientService.selectPclientById(id);
//                if (pclient == null) {
//                    return error("id error");
//                }
                if (StringUtils.isBlank(clientModel.getCompanyName())) {
                    clientModel.setCompanyName("");
                }
                if (StringUtils.isBlank(clientModel.getAddress())) {
                    clientModel.setAddress("");
                }
                if (clientModel.getFileType() == 1) {
                    // 不跨境版 加上日期 直接下载
                    TandcData1 tandcData1 = TandcData1.builder()
                            .dateTime(DateUtils.datePath())
                            .companyName(clientModel.getCompanyName())
                            .signerName(clientModel.getSignerName())
                            .signerPosition(clientModel.getSignerPosition())
                            .build();
                    String filePath = RuoYiConfig.getDownloadPath() + "T&C Jobslink （不跨境版）.docx";
                    File file = new File(filePath);
                    FileOutputStream out = new FileOutputStream(
                            RuoYiConfig.getDownloadPath() + clientModel.getCompanyName() + "T&C Jobslink （不跨境版）" + ".docx");
                    EasyWord.of(file).doWrite(tandcData1).toOutputStream(out);
                    Map result = new HashMap();
                    result.put("filename", clientModel.getCompanyName() + "T&C Jobslink （不跨境版）" + ".docx");
                    return success(result);
                } else if (clientModel.getFileType() == 2) {
                    // 不跨境版 加上日期 直接下载
                    TandcData2 tandcData2 = TandcData2.builder()
                            .companyName(clientModel.getCompanyName())
                            .address(clientModel.getAddress())
                            .dateTime(DateUtils.datePath())
                            .signerName(clientModel.getSignerName())
                            .signerPosition(clientModel.getSignerPosition())
                            .build();
                    String filePath = RuoYiConfig.getDownloadPath() + "T&C Jobslink(专才版）long term.docx";
                    File file = new File(filePath);
                    FileOutputStream out = new FileOutputStream(
                            RuoYiConfig.getDownloadPath() + clientModel.getCompanyName() + "T&C Jobslink(专才版）long term" + ".docx");
                    EasyWord.of(file).doWrite(tandcData2).toOutputStream(out);
                    Map result = new HashMap();
                    result.put("filename", clientModel.getCompanyName() + "T&C Jobslink(专才版）long term" + ".docx");
                    return success(result);
                } else {
                    // 不跨境版 加上日期 直接下载
                    TandcData2 tandcData2 = TandcData2.builder()
                            .companyName(clientModel.getCompanyName())
                            .address(clientModel.getAddress())
                            .dateTime(DateUtils.datePath())
                            .signerName(clientModel.getSignerName())
                            .signerPosition(clientModel.getSignerPosition())
                            .build();
                    String filePath = RuoYiConfig.getDownloadPath() + "T&C Jobslink(专才版）One-Off.docx";
                    File file = new File(filePath);
                    FileOutputStream out = new FileOutputStream(
                            RuoYiConfig.getDownloadPath() + clientModel.getCompanyName() + "T&C Jobslink(专才版）One-Off" + ".docx");
                    EasyWord.of(file).doWrite(tandcData2).toOutputStream(out);
                    Map result = new HashMap();
                    result.put("filename", clientModel.getCompanyName() + "T&C Jobslink(专才版）One-Off" + ".docx");
                    return success(result);
                }
            } else if(clientModel.getType() == 2) {
                return error("type error");
            } else {
                return error("type error");
            }
        } catch (Exception e) {
            // 重置response
            return error("fail");
        }
    }

    /**
     * 查询【请填写功能名称】列表
     */
//    @PreAuthorize("@ss.hasPermi('system:pclient:list')")
    @GetMapping("/list")
    public TableDataInfo list(Pclient pclient)
    {
        startPage();
        //查询当前用户角色
//        SysUser user = SecurityUtils.getLoginUser().getUser();
//        // 角色集合
//        Set<String> roles = permissionService.getRolePermission(user);
//        if (roles != null && roles.size() > 0) {
//            if (roles.contains("admin") || roles.contains("boss")) {
//            } else {
//                pclient.setCreateUserId(getUsername());
//            }
//        } else {
//            pclient.setCreateUserId(getUsername());
//        }
        List<Pclient> list = pclientService.selectPclientList(pclient);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setStaff(list.get(i).getCreateUserId());
            }
        }
        return getDataTable(list);
    }

    private boolean isNumeric(String str){
        for (int i = str.length();--i>=0;){
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }

    /**
     * 导出【请填写功能名称】列表
     */
//    @PreAuthorize("@ss.hasPermi('system:pclient:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Pclient pclient)
    {
        List<Pclient> list = pclientService.selectPclientList(pclient);
        ExcelUtil<Pclient> util = new ExcelUtil<Pclient>(Pclient.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:pclient:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pclientService.selectPclientById(id));
    }

    @Resource
    private IClientService clientService;

    @GetMapping(value = "/check/{name}")
    public AjaxResult checkName(@PathVariable("name") String name)
    {
        Pclient pclient = new Pclient();
        pclient.setName1(name);
        List<Pclient> pclients = pclientService.selectPclientList(pclient);
        if (pclients != null && pclients.size() > 0) {
            return error("Name already exists");
        }
        Client client = new Client();
        client.setName1(name);
        List<Client> clients = clientService.selectClientList(client);
        if (clients != null && clients.size() > 0) {
            return error("Name already exists");
        }
        return toAjax(1);
    }

    /**
     * 新增【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:pclient:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Pclient pclient)
    {
        pclient.setCreateTime(new Date());
        pclient.setCreateAt(new Date());
        pclient.setCreateUserId(String.valueOf(getUsername()));
        return toAjax(pclientService.insertPclient(pclient));
    }

    /**
     * 修改【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:pclient:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Pclient pclient)
    {
        pclient.setUpdateUserid(getUsername());
        pclient.setUpdateTime(new Date());
        return toAjax(pclientService.updatePclient(pclient));
    }

    /**
     * 删除【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:pclient:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pclientService.deletePclientByIds(ids));
    }
}
